import sys
from loguru import logger
import inspect
import uuid

class logutils():
    def __init__(self, filename, rotation="00:00", retention="14 days", serialize=False):
        """

        :param filename: 日志文件名称
        :param rotation: 轮转时间
        :param retention: 清理间隔
        :param serialize: 是否序列化,将日志转换为json
        """

        self.logger = logger

        self.logger.configure(
            handlers=[
                {
                    "sink": filename,  # 日志文件名
                    "format": "<green>{time:YYYY-MM-DD HH:mm:ss}</green> <level>{level: <8}</level> <white>{extra[uuid]}</white>  <level>{extra[modules]}</level>  <level>{extra[filename]}</level>:<level>{extra[lineno]: <8}</level> <level>{extra[msg]}</level>",
                    "rotation": rotation,  # 日志文件大小限制
                    "retention": retention,  # 日志文件保留时间
                    "compression": "zip",  # 日志文件压缩格式
                    "serialize": serialize,
                    "encoding": "utf-8",
                    "diagnose": False
                },
                {
                    "sink": sys.stdout,  # 日志文件名
                    "format": "<green>{time:YYYY-MM-DD HH:mm:ss}</green> <level>{level: <8}</level> <white>{extra[uuid]}</white>  <level>{extra[modules]}</level>  <level>{extra[filename]}</level>:<level>{extra[lineno]: <8}</level> <level>{extra[msg]}</level>",
                }
            ]
        )

    def info(self, args,uuids=None):
        # 获取当前帧
        current_frame = inspect.currentframe()
        # 获取调用栈信息
        stack = inspect.getouterframes(current_frame)
        # 获取父函数的位置
        parent_frame = stack[1]
        parent_file = parent_frame.filename.__str__()
        parent_line = parent_frame.lineno.__str__()
        parent_function = parent_frame.function.__str__()
        if parent_function == '<module>':
            parent_function = "None"
        if uuids is None:
            uuids = uuid.uuid4().__str__()

        if isinstance(args, list) or isinstance(args, tuple) and len(args) > 1:
            self.logger.info("",msg=' '.join([str(i) for i in args]),
                             uuid=uuids,filename=parent_file, modules=parent_function, lineno=parent_line)
        elif isinstance(args, dict) and args:
            self.logger.info("",msg=','.join([f'{k}={v}' for k, v in args.items()]),
                             uuid=uuids,filename=parent_file, modules=parent_function, lineno=parent_line)
        elif isinstance(args, str):
            self.logger.info("",msg=args, uuid=uuids,filename=parent_file, modules=parent_function, lineno=parent_line)
        else:
            self.logger.info("",msg=str(args), uuid=uuids,filename=parent_file, modules=parent_function, lineno=parent_line)

    def debug(self,args,uuids=None):
        # 获取当前帧
        current_frame = inspect.currentframe()
        # 获取调用栈信息
        stack = inspect.getouterframes(current_frame)
        # 获取父函数的位置
        parent_frame = stack[1]
        parent_file = parent_frame.filename.__str__()
        parent_line = parent_frame.lineno.__str__()
        parent_function = parent_frame.function.__str__()
        if parent_function == '<module>':
            parent_function = "None"
        if uuids is None:
            uuids = uuid.uuid4().__str__()
        if isinstance(args, list) or isinstance(args, tuple) and len(args) > 1:
            self.logger.debug("",msg=' '.join([str(i) for i in args]),
                              uuid=uuids,filename=parent_file, modules=parent_function, lineno=parent_line)
        elif isinstance(args, dict) and args:
            self.logger.debug("",msg=','.join([f'{k}={v}' for k, v in args.items()]),
                              uuid=uuids,filename=parent_file, modules=parent_function, lineno=parent_line)
        elif isinstance(args, str):
            self.logger.debug("",msg=args, uuid=uuids,filename=parent_file, modules=parent_function, lineno=parent_line)
        else:
            self.logger.debug("",msg=str(args), uuid=uuids,filename=parent_file, modules=parent_function, lineno=parent_line)

    def error(self, args,uuids=None):
        # 获取当前帧
        current_frame = inspect.currentframe()
        # 获取调用栈信息
        stack = inspect.getouterframes(current_frame)
        # 获取父函数的位置
        parent_frame = stack[1]
        parent_file = parent_frame.filename.__str__()
        parent_line = parent_frame.lineno.__str__()
        parent_function = parent_frame.function.__str__()
        if parent_function == '<module>':
            parent_function = "None"
        if uuids is None:
            uuids = uuid.uuid4().__str__()
        if isinstance(args, list) or isinstance(args, tuple) and len(args) > 1:
            self.logger.error("",msg=' '.join([str(i) for i in args]),
                              uuid=uuids,filename=parent_file, modules=parent_function, lineno=parent_line)
        elif isinstance(args, dict) and args:
            self.logger.error("",msg=','.join([f'{k}={v}' for k, v in args.items()]),
                              uuid=uuids,filename=parent_file, modules=parent_function, lineno=parent_line)
        elif isinstance(args, str):
            self.logger.error("",msg=args, uuid=uuids,filename=parent_file, modules=parent_function, lineno=parent_line)
        else:
            self.logger.error("",msg=str(args), uuid=uuids,filename=parent_file, modules=parent_function, lineno=parent_line)


if __name__ == '__main__':
    a = logutils("info.log",serialize=True)
    a.info(["zhangsan", "lisi"])
    a.info({"a": 1, "b": 2})
    a.info("zah")
    a.error("zhangsan")
    a.debug("zhangsan")
